<template>
    <div>
        <basic-container>
            <div class="app-container">
                <!-- 查询条件表单 -->
                <el-form :model="otherQuery" ref="queryForm" size="small" :inline="true">

                    <el-form-item label="设备名称">
                        <el-select style="width: 180px;" v-model="otherQuery.facility_id" placeholder="请选择" clearable @change="saveToCache">
                            <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                                :value="item.facility_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
           
                    <el-form-item label="查询方式">
                        <el-select style="width: 240px;" v-model="otherQuery.query_type" placeholder="请选择">
                            <el-option label="根据当前生产机种查询SOP" :value="1"></el-option>
                            <el-option label="根据选择机种查询sop" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
              
                    <el-form-item label="机种名称">
                        <el-select style="width: 180px;" v-model="otherQuery.aircraft_id" placeholder="请选择" clearable @change="saveToCache">
                            <el-option v-for="item in roleOptions" :key="item.aircraft_id" :label="item.aircraft"
                                :value="item.aircraft_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                  

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini"
                            @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <!-- 简化的加载状态显示 -->
                <div v-if="loading" class="loading-container">
                    <el-card class="loading-card" shadow="hover">
                        <div class="loading-content">
                            <i class="el-icon-loading"></i>
                            <span>正在加载PDF文档...</span>
                </div>
                    </el-card>
                        </div>
                        
                <!-- PDF显示区域 -->
                <div v-if="currentPdfSrc && !loading" class="pdf-display-container">
                    <el-card class="pdf-card" shadow="hover">
                        <div slot="header" class="pdf-header">
                            <span class="pdf-title">PDF文档查看</span>
                                <div class="pdf-controls">
                                <el-button @click="prevPage" :disabled="dialogCurrentPage <= 1" size="small">上一页</el-button>
                                <span class="page-info">{{ dialogCurrentPage }} / {{ dialogTotalPages }}</span>
                                <el-button @click="nextPage" :disabled="dialogCurrentPage >= dialogTotalPages" size="small">下一页</el-button>
                                <el-button @click="zoomOut" :disabled="dialogScale <= 0.5" size="small">缩小</el-button>
                                <span class="zoom-info">{{ Math.round(dialogScale * 100) }}%</span>
                                                                <el-button @click="zoomIn" :disabled="dialogScale >= 3" size="small">放大</el-button>
                                <!-- 移除调试按钮 -->
                                <!-- <el-button @click="debugCanvas" type="warning" size="small">调试Canvas</el-button> -->
                                </div>
                            </div>
                        <div class="pdf-content">
                            <canvas ref="mainPdfCanvas" class="main-pdf-canvas"></canvas>
                        </div>
                    </el-card>
                </div>
                
                <!-- 空状态显示 测试push-->
                <div v-if="!currentPdfSrc && !loading" class="empty-container">
                    <el-empty description="请选择查询条件并点击搜索来查看PDF文档"></el-empty>
                </div>

            </div>
        </basic-container>

        <!-- PDF查看对话框 -->
        <el-dialog title="PDF查看" :visible.sync="pdfDialogVisible" width="90%" top="5vh">
            <div style="height: 70vh; overflow: auto; text-align: center;">
                <canvas v-if="currentPdfSrc" ref="dialogPdfCanvas" class="dialog-pdf-canvas"></canvas>
                <div v-else style="text-align: center; padding: 50px;">
                    <el-empty description="PDF文件加载失败"></el-empty>
                </div>
            </div>
            <div v-if="currentPdfSrc" class="dialog-pdf-controls">
                <el-button @click="prevPage" :disabled="dialogCurrentPage <= 1">上一页</el-button>
                <span class="page-info">{{ dialogCurrentPage }} / {{ dialogTotalPages }}</span>
                <el-button @click="nextPage" :disabled="dialogCurrentPage >= dialogTotalPages">下一页</el-button>
                <el-button @click="zoomOut" :disabled="dialogScale <= 0.5">缩小</el-button>
                <span class="zoom-info">{{ Math.round(dialogScale * 100) }}%</span>
                <el-button @click="zoomIn" :disabled="dialogScale >= 3">放大</el-button>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="pdfDialogVisible = false">关闭</el-button>
            </span>
        </el-dialog>


    </div>
</template>

<script>
// 导入PDF.js库（使用require方式避免ES6模块问题）
const pdfjsLib = require('pdfjs-dist');

// 设置worker路径（2.5.207版本）
pdfjsLib.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry');

// 简化的PDF.js加载函数
// const loadPDFJS = () => {
//   return Promise.resolve(pdfjsLib);
// };

import {
    getkindList,
    getStation,
    getdkind,
    getdTaskkind
} from "@/api/arftsop";

export default {
    data() {
        return {
            tableTile: ['机种名称', '单工站SOP'],
            checked: false,
            roleOptions: [],
            menuList: [],
            tabPosition: "left",
            loading: false,
            // 弹出层标题
            title: "",
            open: false,
            isAdd: false, // 是否为新增操作
            
            // 查询参数
            otherQuery: {
                facility_id: null,
                aircraft_id: null,
                query_type: 1 // 默认根据当前生产机种查询
            },
            
            // PDF查看相关
            pdfDialogVisible: false,
            currentPdfSrc: null,
            currentPdfDoc: null,
            dialogCurrentPage: 1,
            dialogTotalPages: 1,
            dialogScale: 1,
            isInitialLoad: true // 标记是否为初始加载
        };
    },
    created() {

    },

    async mounted() {
        try {
            if (pdfjsLib) {
                this.pdfjsLib = pdfjsLib;
            } else {
                console.error('PDF.js未正确导入');
            }
        } catch (error) {
            console.error('PDF.js初始化失败:', error);
        }
        
        // 从本地缓存加载选择项
       
        
        this.getList();
        this.getdkindList();
        this.loadFromCache();
    },
 
    methods: {
        // 查看PDF文件
        viewPDF(row) {
            console.log('查看PDF，行数据:', row);
            
            // 优先级1: 使用PDF缓冲区数据
            if (row.pdf_buffer) {
                console.log('使用行数据中的PDF缓冲区');
                try {
                    if (this.validatePDFData(row.pdf_buffer)) {
                        this.loadPDFForDialog(row.pdf_buffer);
                    return;
                } else {
                        console.error('PDF缓冲区数据验证失败');
                    }
                } catch (error) {
                    console.error('行数据PDF缓冲区处理失败:', error);
                }
            }
            // 优先级2: 使用PDF原始内容
            else if (row.pdf_raw_content) {
                console.log('使用行数据中的PDF原始内容');
                try {
                    // 使用安全的转换方法
                    const byteArray = this.convertPDFStringToUint8Array(row.pdf_raw_content);
                    if (byteArray && this.validatePDFData(byteArray)) {
                    this.loadPDFForDialog(byteArray);
                    return;
                    } else {
                        console.error('PDF数据验证失败');
                    }
                } catch (error) {
                    console.error('行数据PDF原始内容解析失败:', error);
                }
            }
            // 优先级2: 使用base64数据
            else if (row.pdf_base64) {
                console.log('使用行数据中的base64数据');
                try {
                    const byteCharacters = atob(row.pdf_base64);
                    const byteNumbers = new Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const byteArray = new Uint8Array(byteNumbers);
                    this.loadPDFForDialog(byteArray);
                    return;
                } catch (error) {
                    console.error('行数据PDF base64解析失败:', error);
                }
            }
            
            // 如果没有base64数据，则调用getStation接口
            console.log('没有base64数据，调用getStation接口');
            const queryParams = {
                facility_id: row.facility_id || null,
                aircraft_id: row.aircraft_id || null,
                query_type: 1 // 根据当前机种查询，1=根据当前机种查询，0=根据参数查询
            };
            
            // 移除空值参数
            Object.keys(queryParams).forEach(key => {
                if (queryParams[key] === null || queryParams[key] === undefined) {
                    delete queryParams[key];
                }
            });
            
            console.log('获取PDF查询参数:', queryParams);
            
            getStation(queryParams).then((res) => {
                console.log('PDF响应:', res);
                console.log('响应数据类型:', typeof res.data);
                console.log('响应是否为ArrayBuffer:', res.data instanceof ArrayBuffer);
                
                // 处理ArrayBuffer响应
                if (res.data instanceof ArrayBuffer) {
                    console.log('接收到ArrayBuffer，大小:', res.data.byteLength);
                    try {
                        const uint8Array = new Uint8Array(res.data);
                        
                        // 检查PDF头部
                        const header = Array.from(uint8Array.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
                        console.log('ArrayBuffer PDF头部:', header);
                        
                        if (header === '%PDF' && this.validatePDFData(uint8Array)) {
                            this.loadPDFForDialog(uint8Array);
                            console.log('PDF文件加载成功');
                        } else {
                            this.$message.error('PDF数据验证失败');
                            console.error('PDF ArrayBuffer无效或损坏');
                        }
                    } catch (error) {
                        this.$message.error('PDF文件解析失败');
                        console.error('PDF ArrayBuffer解析错误:', error);
                    }
                }
                // 处理字符串响应（向后兼容）
                else if (res.data && typeof res.data === 'string') {
                    if (res.data.startsWith('%PDF')) {
                        // PDF原始内容
                        console.log('接收到PDF原始内容');
                        try {
                            // 使用安全的转换方法
                            const byteArray = this.convertPDFStringToUint8Array(res.data);
                            if (byteArray && this.validatePDFData(byteArray)) {
                            this.loadPDFForDialog(byteArray);
                            console.log('PDF文件加载成功');
                            } else {
                                this.$message.error('PDF数据验证失败');
                                console.error('PDF数据无效或损坏');
                            }
                        } catch (error) {
                            this.$message.error('PDF文件解析失败');
                            console.error('PDF原始内容解析错误:', error);
                        }
                    } else {
                        // 可能是base64字符串
                        console.log('尝试作为base64处理');
                        try {
                            const byteCharacters = atob(res.data);
                            const byteNumbers = new Array(byteCharacters.length);
                            for (let i = 0; i < byteCharacters.length; i++) {
                                byteNumbers[i] = byteCharacters.charCodeAt(i);
                            }
                            const byteArray = new Uint8Array(byteNumbers);
                            this.loadPDFForDialog(byteArray);
                            console.log('PDF文件加载成功');
                        } catch (error) {
                            this.$message.error('PDF文件解析失败');
                            console.error('PDF数据解析错误:', error);
                        }
                    }
                } else {
                    this.$message.warning('该记录没有PDF文件');
                }
            }).catch(error => {
                console.error('获取PDF失败:', error);
                this.$message.error('获取PDF文件失败');
            });
        },

        handleExport() {
            this.$confirm('是否将数据导出为Excel文档？').then(() => {
                const params = new URLSearchParams();
                this.otherQuery.aircraft_id == null ? '' : params.append('aircraft_id', this.otherQuery.aircraft_id);
                this.otherQuery.facility_id == null ? '' : params.append('facility_id', this.otherQuery.facility_id);
                const url = new URL('http://192.168.20.252:8080/api/query/sop/output');
                url.search = params.toString();
                window.location.href = url.toString();
            })
        },
        
        gitMeassList() {
            this.loading = true;
            
            // 构建查询参数
            const queryParams = {
                facility_id: this.otherQuery.facility_id || null,
                aircraft_id: this.otherQuery.aircraft_id || null,
                query_type: this.otherQuery.query_type !== undefined ? this.otherQuery.query_type : 1
            };
            
            // 移除空值参数
            Object.keys(queryParams).forEach(key => {
                if (queryParams[key] === null || queryParams[key] === undefined) {
                    delete queryParams[key];
                }
            });
            
            console.log('查询PDF文档:', queryParams);
            console.log('调用来源:', this.isInitialLoad ? '页面初始化' : '用户搜索');
            
            getStation(queryParams).then((res) => {
                console.log('✅ API响应成功');
                console.log('响应类型:', typeof res.data);
                console.log('是否为ArrayBuffer:', res.data instanceof ArrayBuffer);
                console.log('数据大小:', res.data.byteLength || res.data.length);
                
                // 处理ArrayBuffer响应
                if (res.data instanceof ArrayBuffer) {
                    console.log('✅ 接收到ArrayBuffer，开始处理...');
                    const uint8Array = new Uint8Array(res.data);
                    
                    // 验证PDF头部
                    const header = Array.from(uint8Array.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
                    console.log('PDF头部:', header);
                    
                    if (header === '%PDF') {
                        console.log('✅ PDF头部验证通过，开始渲染');
                        this.renderPDF(uint8Array);
                } else {
                        console.error('❌ PDF头部验证失败');
                        this.loading = false;
                        this.$message.error('PDF数据格式错误');
                    }
                } 
                // 处理字符串响应（当前情况）
                else if (typeof res.data === 'string' && res.data.startsWith('%PDF')) {
                    console.log('✅ 接收到PDF字符串数据，开始转换...');
                    console.log('PDF字符串前50字符:', res.data.substring(0, 50));
                    
                    // 使用我们改进的转换方法
                    const uint8Array = this.convertPDFStringToUint8ArrayImproved(res.data);
                    if (uint8Array) {
                        console.log('✅ 字符串转换成功，开始渲染PDF');
                        this.renderPDF(uint8Array);
                } else {
                        console.error('❌ 字符串转换失败');
                    this.loading = false;
                        this.$message.error('PDF数据转换失败');
                    }
                } 
                else {
                    console.error('❌ 未识别的数据格式');
                    console.log('实际数据类型:', typeof res.data);
                    console.log('数据开头:', res.data.toString().substring(0, 100));
                    this.loading = false;
                    this.$message.error('数据格式不正确');
                }
            }).catch(error => {
                this.loading = false;
                console.error('API调用失败:', error);
                this.$message.error('获取PDF数据失败: ' + error.message);
            });
        },
        
        // 处理无效PDF
        handleInvalidPDF() {
            this.loading = false;
            this.$message.error('接收到的PDF数据格式无效');
        },

        // 处理无效响应
        handleInvalidResponse() {
            this.loading = false;
            this.$message.error('服务器返回了无效的数据格式');
        },

        // 直接加载PDF数据（ArrayBuffer）
        loadPDFData(uint8Array) {
            console.log('✅ 加载正确的PDF二进制数据，大小:', uint8Array.length);
            
            // 验证PDF头部
            const header = Array.from(uint8Array.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
            console.log('PDF头部验证:', header);
            
            if (header === '%PDF') {
                // 直接渲染，不需要转换
                this.renderPDF(uint8Array);
            } else {
                this.loading = false;
                this.$message.error('PDF格式验证失败');
            }
        },
        
        // 从字符串加载PDF
        loadPDFFromString(pdfString) {
            console.log('转换PDF字符串数据');
            try {
                // 转换PDF字符串为二进制数据
                const uint8Array = this.convertPDFStringToUint8Array(pdfString);
                if (uint8Array) {
                    this.renderPDF(uint8Array);
                } else {
                            this.loading = false;
                    this.$message.error('PDF数据转换失败');
                }
                } catch (error) {
                            this.loading = false;
                this.$message.error('PDF数据处理失败');
                console.error('PDF转换错误:', error);
            }
        },
        
        // 渲染PDF到页面
        async renderPDF(uint8Array) {
            try {
                this.loading = true;
                console.log('开始渲染PDF，大小:', uint8Array.length);
                
                // 检测PDF类型
                const isLinearized = this.detectLinearizedPDF(uint8Array);
                console.log('PDF类型:', isLinearized ? '线性化PDF' : '标准PDF');

                // 尝试多种PDF.js配置来处理损坏的PDF
                const configs = [
                    // 配置1: 容错模式
                    {
                        name: '容错模式',
                        options: {
                            data: uint8Array,
                            verbosity: 1,
                            stopAtErrors: false,
                            ignoreErrors: true,
                            disableAutoFetch: true,
                            disableStream: true,
                            disableRange: true,
                            // 强制使用系统字体
                            useSystemFonts: true,
                            // 禁用字体子集化
                            disableFontFace: true,
                            // 最大图片尺寸
                            maxImageSize: 16777216,
                            // 启用工作线程
                            isEvalSupported: false,
                            // CMap设置
                            cMapUrl: '/static/pdfjs/cmaps/',
                            cMapPacked: true,
                            standardFontDataUrl: '/static/pdfjs/standard_fonts/'
                        }
                    },
                    // 配置2: 图像优先模式（针对图片PDF）
                    {
                        name: '图像优先模式',
                        options: {
                            data: uint8Array,
                            verbosity: 0,
                            stopAtErrors: false,
                            disableAutoFetch: false,
                            disableStream: false,
                            disableRange: false,
                            useSystemFonts: false,
                            disableFontFace: false,
                            maxImageSize: -1, // 无限制
                            isEvalSupported: true,
                            fontExtraProperties: true
                        }
                    },
                    // 配置3: 最小化模式
                    {
                        name: '最小化模式',
                        options: {
                            data: uint8Array,
                            verbosity: 0
                        }
                    }
                ];

                let pdfDoc = null;
                let usedConfig = null;

                // 尝试不同的配置
                for (const config of configs) {
                    try {
                        console.log(`尝试使用${config.name}加载PDF...`);
                        const loadingTask = this.pdfjsLib.getDocument(config.options);
                        pdfDoc = await loadingTask.promise;
                        usedConfig = config.name;
                        console.log(`✅ ${config.name}加载成功`);
                        break;
                        } catch (error) {
                        console.warn(`❌ ${config.name}失败:`, error.message);
                        continue;
                    }
                }

                if (!pdfDoc) {
                    throw new Error('所有PDF加载配置都失败了');
                }
                
                // 设置PDF文档信息
                this.currentPdfDoc = pdfDoc;
                this.currentPdfSrc = 'loaded';
                this.dialogCurrentPage = 1;
                this.dialogTotalPages = pdfDoc.numPages;
                this.dialogScale = 1.3; // 增加默认缩放比例从1.0到1.3
                this.loading = false;
                
                console.log(`PDF加载成功，共 ${pdfDoc.numPages} 页，使用配置: ${usedConfig}`);
                this.$message.success(`PDF文档加载成功 (${usedConfig})`);
                
                // 渲染第一页到主页面
                this.$nextTick(() => {
                    console.log('开始渲染第一页到主页面canvas');
                    this.renderPDFPageWithFallback(pdfDoc, 1, this.$refs.mainPdfCanvas, 1.3);
                });
                
            } catch (error) {
                this.loading = false;
                console.error('PDF渲染失败:', error);
                
                // 显示更友好的错误信息
                if (error.message.includes('Invalid stream') || error.message.includes('FCHECK')) {
                    this.$message.error('PDF文件数据流损坏，无法正常显示内容');
                    console.error('建议：请联系数据提供方检查PDF文件完整性');
                } else if (error.name === 'InvalidPDFException') {
                    this.$message.error('PDF文件结构无效，无法渲染');
                } else {
                    this.$message.error('PDF加载失败: ' + error.message);
                }
            }
        },
        
        

        getdkindList() {
            getdkind().then((res) => {
                this.roleOptions = res.data.data;
                console.log(this.roleOptions, '机种列表');
            });
        },
        
        // 获取设备列表
        getList() {
            const queryParams = {
                index: 1,
                size: 1000,
            };
            getkindList(queryParams).then((response) => {
                this.menuList = response.data.data;
                console.log(this.menuList, "单工站设备列表");
            });
        },
        
        // 查询处理
        handleQuery() {
            console.log('点击搜索按钮');
            this.gitMeassList();
        },
        
        // 重置查询
        resetQuery() {
            this.otherQuery = {
                facility_id: null,
                aircraft_id: null,
                query_type: 1
            };
        },
        
        querySearchAsync(queryString) {
            if (queryString == null) return;

            let quey = {
                name: queryString,
            };
            getdTaskkind(quey).then((res) => {
                this.restaurants = res.data.data;
            });
        },
        

        
        // 全屏模式下一页
        nextFullscreenPage() {
            if (this.fullscreenCurrentPage < this.fullscreenTotalPages) {
                this.fullscreenCurrentPage++;
                this.renderPDFPage(this.fullscreenPdfDoc, this.fullscreenCurrentPage, this.$refs.fullscreenPdfCanvas, this.fullscreenScale);
            }
        },
        
        // 全屏模式上一页
        prevFullscreenPage() {
            if (this.fullscreenCurrentPage > 1) {
                this.fullscreenCurrentPage--;
                this.renderPDFPage(this.fullscreenPdfDoc, this.fullscreenCurrentPage, this.$refs.fullscreenPdfCanvas, this.fullscreenScale);
            }
        },
        
        // 全屏模式放大
        fullscreenZoomIn() {
            if (this.fullscreenScale < 3) {
                this.fullscreenScale += 0.25;
                this.renderPDFPage(this.fullscreenPdfDoc, this.fullscreenCurrentPage, this.$refs.fullscreenPdfCanvas, this.fullscreenScale);
            }
        },
        
        // 全屏模式缩小
        fullscreenZoomOut() {
            if (this.fullscreenScale > 0.5) {
                this.fullscreenScale -= 0.25;
                this.renderPDFPage(this.fullscreenPdfDoc, this.fullscreenCurrentPage, this.$refs.fullscreenPdfCanvas, this.fullscreenScale);
            }
        },
        
        // 上一页
        prevPage() {
            if (this.dialogCurrentPage > 1) {
                this.dialogCurrentPage--;
                this.renderPDFPage(this.currentPdfDoc, this.dialogCurrentPage, this.$refs.mainPdfCanvas, this.dialogScale);
            }
        },
        
        // 下一页
        nextPage() {
            if (this.dialogCurrentPage < this.dialogTotalPages) {
                this.dialogCurrentPage++;
                this.renderPDFPage(this.currentPdfDoc, this.dialogCurrentPage, this.$refs.mainPdfCanvas, this.dialogScale);
            }
        },
        
        // 放大
        zoomIn() {
            if (this.dialogScale < 3) {
                this.dialogScale += 0.25;
                this.renderPDFPage(this.currentPdfDoc, this.dialogCurrentPage, this.$refs.mainPdfCanvas, this.dialogScale);
            }
        },
        
        // 缩小
        zoomOut() {
            if (this.dialogScale > 0.5) {
                this.dialogScale -= 0.25;
                this.renderPDFPage(this.currentPdfDoc, this.dialogCurrentPage, this.$refs.mainPdfCanvas, this.dialogScale);
            }
        },
        

        
        // 使用PDF.js渲染PDF
        async renderPDFFromBuffer(buffer, item, index) {
            try {
                const pdfDoc = await pdfjsLib.getDocument({ data: buffer }).promise;
                this.$set(item, 'pdfDoc', pdfDoc);
                this.$set(item, 'totalPages', pdfDoc.numPages);
                this.$set(item, 'currentPage', 1);
                this.$set(item, 'pdfSrc', 'loaded'); // 标记为已加载
                this.$set(item, 'loading', false);
                
                // 渲染第一页
                this.$nextTick(() => {
                    this.renderPDFPage(pdfDoc, 1, `pdfCanvas${index}`, 1.2);
                });
                
                console.log(`PDF ${index + 1} 加载成功，共 ${pdfDoc.numPages} 页`);
            } catch (error) {
                this.$set(item, 'loading', false);
                console.error(`PDF ${index + 1} 渲染失败:`, error);
            }
        },
        
        // 渲染PDF页面到Canvas
        async renderPDFPage(pdfDoc, pageNum, canvasRef, scale = 1) {
            try {
                const page = await pdfDoc.getPage(pageNum);
                const viewport = page.getViewport({ scale });
                
                let canvas;
                if (typeof canvasRef === 'string') {
                    canvas = this.$refs[canvasRef];
                    if (Array.isArray(canvas)) {
                        canvas = canvas[0];
                    }
                } else {
                    canvas = canvasRef;
                }
                
                if (!canvas) {
                    return;
                }
                
                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                
                // 完全清除Canvas内容
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.fillStyle = 'white';
                context.fillRect(0, 0, canvas.width, canvas.height);
                
                const renderContext = {
                    canvasContext: context,
                    viewport: viewport,
                    background: 'white',
                    intent: 'display'
                };
                
                const renderTask = page.render(renderContext);
                await renderTask.promise;
                
                // 确保没有任何测试代码
                // 所有测试相关的代码都已被移除
                
            } catch (error) {
                console.error('渲染PDF页面失败:', error);
            }
        },
        
        // 添加一个强制重新渲染的方法
        forceRerender() {
            if (this.currentPdfDoc && this.$refs.mainPdfCanvas) {
                // 完全清除Canvas
                const canvas = this.$refs.mainPdfCanvas;
                const context = canvas.getContext('2d');
                context.clearRect(0, 0, canvas.width, canvas.height);
                
                // 重新渲染当前页面
                this.renderPDFPage(this.currentPdfDoc, this.dialogCurrentPage, canvas, this.dialogScale);
            }
        },
        
        // 新增Canvas内容分析方法
        analyzeCanvasContent(canvas, pageNum) {
            try {
                console.log(`=== Canvas内容分析 - 页面 ${pageNum} ===`);
                
                const context = canvas.getContext('2d');
                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                const pixels = imageData.data;
                
                // 统计像素颜色分布
                let colorStats = {
                    pureWhite: 0,      // 纯白色 (255,255,255)
                    nearWhite: 0,      // 近白色 (240-254)
                    black: 0,          // 黑色 (0-50)
                    gray: 0,           // 灰色 (51-239)
                    colored: 0,        // 彩色
                    transparent: 0     // 透明
                };
                
                let samplePixels = [];
                const sampleSize = Math.min(10000, pixels.length / 4);
                
                for (let i = 0; i < sampleSize * 4; i += 4) {
                    const r = pixels[i];
                    const g = pixels[i + 1];
                    const b = pixels[i + 2];
                    const alpha = pixels[i + 3];
                    
                    // 记录前10个像素作为样本
                    if (samplePixels.length < 10) {
                        samplePixels.push([r, g, b, alpha]);
                    }
                    
                    if (alpha === 0) {
                        colorStats.transparent++;
                    } else if (r === 255 && g === 255 && b === 255) {
                        colorStats.pureWhite++;
                    } else if (r >= 240 && g >= 240 && b >= 240) {
                        colorStats.nearWhite++;
                    } else if (r <= 50 && g <= 50 && b <= 50) {
                        colorStats.black++;
                    } else if (r === g && g === b) {
                        colorStats.gray++;
                    } else {
                        colorStats.colored++;
                    }
                }
                
                console.log('像素颜色统计:', colorStats);
                console.log('样本像素 (前10个):', samplePixels);
                
                // 计算非白色像素比例
                const totalNonWhite = colorStats.black + colorStats.gray + colorStats.colored;
                const nonWhitePercentage = (totalNonWhite / sampleSize) * 100;
                
                console.log(`非白色像素比例: ${nonWhitePercentage.toFixed(2)}%`);
                
                if (nonWhitePercentage < 0.1) {
                    console.warn('⚠️ 检测到PDF内容几乎全是白色，可能的原因:');
                    console.warn('1. PDF文档内容确实是白色文字/图形');
                    console.warn('2. PDF文档是空白页');
                    console.warn('3. PDF渲染配置有问题');
                    console.warn('4. PDF文档损坏或格式不支持');
                } else {
                    console.log('✅ 检测到有效的PDF内容');
                }
                
                // 尝试在不同位置绘制测试内容来验证Canvas是否正常工作
                // context.save();
                // context.fillStyle = 'red';
                // context.fillRect(10, 10, 50, 20);
                // context.fillStyle = 'blue';
                // context.font = '16px Arial';
                // context.fillText('TEST', 70, 25);
                // context.restore();
                
                console.log('已在Canvas上绘制红色矩形和蓝色文字用于测试');
                
            } catch (error) {
                console.error('Canvas内容分析失败:', error);
            }
        },
        
        // 为对话框加载PDF
        async loadPDFForDialog(buffer) {
            let currentBuffer = buffer;
            let retryCount = 0;
            const maxRetries = 2;
            
            while (retryCount <= maxRetries) {
                try {
                    // 添加调试信息
                    console.log(`对话框PDF加载 (尝试 ${retryCount + 1}/${maxRetries + 1})，缓冲区大小:`, currentBuffer.length);
                    console.log('PDF头部字节:', Array.from(currentBuffer.slice(0, 8)).map(b => b.toString(16)).join(' '));
                    
                    // 根据PDF类型设置配置
                    const isLinearized = this.isLinearizedPDF(currentBuffer);
                    console.log('对话框PDF类型:', isLinearized ? '线性化PDF' : '标准PDF');
                    
                    let pdfOptions = {
                        data: currentBuffer,
                        verbosity: 0,
                        stopAtErrors: false,
                        maxImageSize: 1024 * 1024,
                        isEvalSupported: false,
                        useSystemFonts: true
                    };
                    
                    if (isLinearized) {
                        pdfOptions.disableRange = false;
                        pdfOptions.disableStream = false;
                        pdfOptions.disableAutoFetch = false;
                        pdfOptions.stopAtErrors = true;
                    } else {
                        pdfOptions.disableRange = true;
                        pdfOptions.disableStream = true;
                        pdfOptions.disableAutoFetch = true;
                    }
                    
                    const loadingTask = pdfjsLib.getDocument(pdfOptions);
                    
                    const pdfDoc = await loadingTask.promise;
                this.currentPdfDoc = pdfDoc;
                this.currentPdfSrc = 'loaded';
                this.dialogCurrentPage = 1;
                this.dialogTotalPages = pdfDoc.numPages;
                this.dialogScale = 1;
                this.pdfDialogVisible = true;
                
                this.$nextTick(() => {
                    this.renderPDFPage(this.currentPdfDoc, this.dialogCurrentPage, this.$refs.dialogPdfCanvas, this.dialogScale);
                });
                
                    console.log(`对话框PDF加载成功，共 ${pdfDoc.numPages} 页`);
                    return; // 成功退出
                    
            } catch (error) {
                    console.error(`对话框PDF加载失败 (尝试 ${retryCount + 1}):`, error);
                    console.error('错误类型:', error.name);
                    console.error('错误消息:', error.message);
                    
                    if (error.name === 'InvalidPDFException' && retryCount < maxRetries) {
                        console.log('尝试修复PDF数据后重试...');
                        currentBuffer = this.repairPDFData(currentBuffer);
                        retryCount++;
                        continue; // 继续下一次尝试
                    }
                    
                    // 最终失败处理
                    if (error.name === 'InvalidPDFException') {
                        this.$message.error('PDF文件结构无效，无法修复');
                    } else if (error.name === 'MissingPDFException') {
                        this.$message.error('PDF数据缺失');
                    } else {
                        this.$message.error(`PDF文件加载失败: ${error.message}`);
                    }
                    return; // 最终失败退出
                }
            }
        },

        // 添加安全的PDF数据转换方法
        // 安全转换PDF原始内容为Uint8Array
        convertPDFStringToUint8Array(pdfString) {
            // 诊断输入数据
            this.diagnosePDFData(pdfString, 'convertPDFStringToUint8Array输入');
            
            try {
                if (typeof pdfString === 'string') {
                    // 首先尝试处理包含控制字符的PDF字符串
                    const processedBytes = this.processPDFWithControlChars(pdfString);
                    if (processedBytes) {
                        this.diagnosePDFData(processedBytes, 'processPDFWithControlChars输出');
                        return processedBytes;
                    }
                    
                    // 回退到原始方法
                    const bytes = new Uint8Array(pdfString.length);
                    for (let i = 0; i < pdfString.length; i++) {
                        const code = pdfString.charCodeAt(i);
                        // 确保字符码在有效范围内
                        if (code > 255) {
                            console.warn('检测到非Latin-1字符，尝试其他转换方法');
                            const alternativeResult = this.convertPDFStringAlternative(pdfString);
                            // 如果返回Promise，则同步处理
                            if (alternativeResult instanceof Promise) {
                                console.warn('备用方法返回Promise，使用同步方法');
                                // 使用同步的强制转换
                                const syncBytes = new Uint8Array(pdfString.length);
                                for (let j = 0; j < pdfString.length; j++) {
                                    syncBytes[j] = pdfString.charCodeAt(j) & 0xFF;
                                }
                                return syncBytes;
                            }
                            return alternativeResult;
                        }
                        bytes[i] = code;
                    }
                    
                    // 诊断输出数据
                    this.diagnosePDFData(bytes, 'convertPDFStringToUint8Array输出');
                    return bytes;
                }
                return null;
            } catch (error) {
                console.error('PDF字符串转换失败:', error);
                return null;
            }
        },
        
        // 处理包含控制字符的PDF字符串
        processPDFWithControlChars(pdfString) {
            try {
                console.log('尝试处理包含控制字符的PDF数据');
                
                // 检查是否包含回车和换行符
                const hasControlChars = /[\r\n]/.test(pdfString);
                if (!hasControlChars) {
                    console.log('未检测到控制字符，跳过特殊处理');
                    return null;
                }
                
                console.log('检测到回车/换行符，进行特殊处理');
                
                // 方法1: 使用更精确的字节级处理
                // 创建一个临时的Uint8Array来存储原始字节
                const buffer = new ArrayBuffer(pdfString.length);
                const view = new Uint8Array(buffer);
                
                for (let i = 0; i < pdfString.length; i++) {
                    const char = pdfString.charAt(i);
                    const code = pdfString.charCodeAt(i);
                    
                    // 对于控制字符，使用其实际的ASCII值
                    if (char === '\r') {
                        view[i] = 0x0D; // CR
                    } else if (char === '\n') {
                        view[i] = 0x0A; // LF
                    } else if (code <= 255) {
                        view[i] = code;
                    } else {
                        // 对于超出范围的字符，使用低8位
                        view[i] = code & 0xFF;
                    }
                }
                
                // 验证PDF头部
                const header = Array.from(view.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
                console.log('处理后的PDF头部:', header);
                
                if (header === '%PDF') {
                    console.log('控制字符处理成功');
                    return view;
                } else {
                    console.log('控制字符处理后头部验证失败');
                    return null;
                }
                
            } catch (error) {
                console.error('控制字符处理失败:', error);
                return null;
            }
        },
        
        // 备用转换方法
        convertPDFStringAlternative(pdfString) {
            try {
                console.log('使用备用转换方法处理PDF数据');
                
                if (pdfString.startsWith('%PDF')) {
                    // 方法1: 强制使用Latin-1编码处理（忽略高位字符问题）
                    console.log('尝试强制Latin-1编码转换');
                    const bytes = new Uint8Array(pdfString.length);
                    for (let i = 0; i < pdfString.length; i++) {
                        const code = pdfString.charCodeAt(i);
                        // 使用模运算确保字节范围在0-255
                        bytes[i] = code & 0xFF;
                    }
                    
                    // 验证转换结果
                    const header = Array.from(bytes.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
                    console.log('强制转换后的文件头:', header);
                    
                    if (header === '%PDF') {
                        console.log('强制Latin-1转换成功');
                        return bytes;
                    }
                    
                    // 方法2: 尝试ISO-8859-1解码
                    console.log('尝试ISO-8859-1解码');
                    try {
                        // 使用Blob和FileReader进行正确的二进制转换
                        return this.convertUsingBlobMethod(pdfString);
                    } catch (blobError) {
                        console.error('Blob方法转换失败:', blobError);
                    }
                    
                    // 方法3: 直接截断高位字符
                    console.log('使用字符截断方法');
                    const truncatedBytes = new Uint8Array(pdfString.length);
                    for (let i = 0; i < pdfString.length; i++) {
                        const code = pdfString.charCodeAt(i);
                        // 直接截断到8位
                        truncatedBytes[i] = code > 255 ? (code % 256) : code;
                    }
                    return truncatedBytes;
                    
                } else {
                    // 可能是base64编码的数据
                    try {
                        const byteCharacters = atob(pdfString);
                        const byteNumbers = new Array(byteCharacters.length);
                        for (let i = 0; i < byteCharacters.length; i++) {
                            byteNumbers[i] = byteCharacters.charCodeAt(i);
                        }
                        return new Uint8Array(byteNumbers);
                    } catch (base64Error) {
                        console.error('base64解码失败:', base64Error);
                        return null;
                    }
                }
            } catch (error) {
                console.error('备用PDF转换失败:', error);
                return null;
            }
        },
        
        // 使用Blob方法进行二进制转换
        convertUsingBlobMethod(pdfString) {
            return new Promise((resolve, reject) => {
                try {
                    // 创建一个Blob，指定MIME类型为application/pdf
                    const blob = new Blob([pdfString], { type: 'application/pdf' });
                    const reader = new FileReader();
                    
                    reader.onload = function() {
                        const arrayBuffer = reader.result;
                        const uint8Array = new Uint8Array(arrayBuffer);
                        resolve(uint8Array);
                    };
                    
                    reader.onerror = function() {
                        reject(new Error('FileReader读取失败'));
                    };
                    
                    reader.readAsArrayBuffer(blob);
                } catch (error) {
                    reject(error);
                }
            });
        },
        
        // 验证PDF数据有效性
        validatePDFData(uint8Array) {
            if (!uint8Array || uint8Array.length < 8) {
                console.error('PDF数据长度不足:', uint8Array ? uint8Array.length : 'null');
                return false;
            }
            
            // 检查PDF文件头
            const header = Array.from(uint8Array.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
            const isValidPDF = header === '%PDF';
            
            if (!isValidPDF) {
                console.warn('PDF文件头验证失败:', header);
                console.warn('实际字节:', Array.from(uint8Array.slice(0, 8)).map(b => b.toString(16)).join(' '));
                return false;
            }
            
            // 进行更深入的PDF结构验证
            return this.deepValidatePDFStructure(uint8Array);
        },
        
        // 深度验证PDF结构
        deepValidatePDFStructure(uint8Array) {
            try {
                console.log('开始深度PDF结构验证');
                
                // 1. 查找PDF版本信息
                const version = this.extractPDFVersion(uint8Array);
                console.log('PDF版本:', version);
                
                // 2. 检查是否为线性化PDF
                const isLinearized = this.isLinearizedPDF(uint8Array);
                console.log('是否为线性化PDF:', isLinearized);
                
                // 3. 查找xref表和trailer
                const hasXref = this.findXrefTable(uint8Array);
                const hasTrailer = this.findTrailer(uint8Array);
                const hasEOF = this.findEOF(uint8Array);
                
                console.log('PDF结构检查:', {
                    hasXref,
                    hasTrailer,
                    hasEOF,
                    isLinearized
                });
                
                // 4. 基本结构完整性检查
                if (!hasEOF) {
                    console.warn('PDF缺少EOF标记，可能文件截断');
                    return false;
                }
                
                // 5. 线性化PDF的特殊验证
                if (isLinearized) {
                    console.log('检测到线性化PDF，使用宽松验证');
                    // 线性化PDF可能没有传统的trailer结构，这是正常的
                    return true;
                }
                
                return true;
                
            } catch (error) {
                console.error('PDF深度验证失败:', error);
                return false;
            }
        },
        
        // 检查是否为线性化PDF
        isLinearizedPDF(uint8Array) {
            try {
                const headerStr = Array.from(uint8Array.slice(0, 1024))
                    .map(b => String.fromCharCode(b))
                    .join('');
                return headerStr.includes('/Linearized');
            } catch (error) {
                return false;
            }
        },
        
        // 提取PDF版本
        extractPDFVersion(uint8Array) {
            try {
                const headerStr = Array.from(uint8Array.slice(0, 10))
                    .map(b => String.fromCharCode(b))
                    .join('');
                const versionMatch = headerStr.match(/%PDF-(\d+\.\d+)/);
                return versionMatch ? versionMatch[1] : 'unknown';
            } catch (error) {
                return 'unknown';
            }
        },
        
        // 查找xref表
        findXrefTable(uint8Array) {
            try {
                const content = Array.from(uint8Array)
                    .map(b => String.fromCharCode(b))
                    .join('');
                return content.includes('xref');
            } catch (error) {
                return false;
            }
        },
        
        // 查找trailer
        findTrailer(uint8Array) {
            try {
                const content = Array.from(uint8Array)
                    .map(b => String.fromCharCode(b))
                    .join('');
                return content.includes('trailer');
            } catch (error) {
                return false;
            }
        },
        
        // 查找EOF标记
        findEOF(uint8Array) {
            try {
                const lastBytes = Array.from(uint8Array.slice(-20))
                    .map(b => String.fromCharCode(b))
                    .join('');
                return lastBytes.includes('%%EOF');
            } catch (error) {
                return false;
            }
        },
        
        // 修复PDF数据
        repairPDFData(uint8Array) {
            try {
                console.log('尝试修复PDF数据');
                
                // 检查是否为线性化PDF
                const isLinearized = this.isLinearizedPDF(uint8Array);
                
                // 创建修复后的数据副本
                let repairedData = new Uint8Array(uint8Array);
                
                if (isLinearized) {
                    console.log('对线性化PDF进行特殊修复');
                    repairedData = this.repairLinearizedPDF(repairedData);
                } else {
                    console.log('对标准PDF进行修复');
                    repairedData = this.repairStandardPDF(repairedData);
                }
                
                console.log('PDF修复完成，新大小:', repairedData.length);
                return repairedData;
                
            } catch (error) {
                console.error('PDF修复失败:', error);
                return uint8Array; // 返回原始数据
            }
        },
        
        // 修复线性化PDF
        repairLinearizedPDF(uint8Array) {
            console.log('执行线性化PDF修复');
            
            // 1. 修复PDF头部后的潜在问题
            const headerEndIndex = this.findHeaderEnd(uint8Array);
            if (headerEndIndex > 0) {
                console.log('线性化PDF头部结束位置:', headerEndIndex);
                
                // 检查linearization dictionary后的数据
                for (let i = headerEndIndex; i < Math.min(headerEndIndex + 100, uint8Array.length); i++) {
                    // 替换可能导致解析问题的控制字符
                    if (uint8Array[i] === 0x00 || (uint8Array[i] > 127 && uint8Array[i] < 160)) {
                        console.log(`修复线性化PDF位置 ${i} 的字符: ${uint8Array[i].toString(16)} -> 20`);
                        uint8Array[i] = 0x20; // 空格
                    }
                }
            }
            
            // 2. 确保文件结构完整
            this.ensurePDFEnding(uint8Array);
            
            return uint8Array;
        },
        
        // 修复标准PDF
        repairStandardPDF(uint8Array) {
            console.log('执行标准PDF修复');
            
            // 1. 检查并修复文件头后的异常字符
            const headerEndIndex = this.findHeaderEnd(uint8Array);
            if (headerEndIndex > 0) {
                console.log('找到PDF头部结束位置:', headerEndIndex);
                
                // 检查头部后是否有异常的高位字符
                for (let i = headerEndIndex; i < Math.min(headerEndIndex + 20, uint8Array.length); i++) {
                    if (uint8Array[i] > 127 && uint8Array[i] < 160) {
                        // 这些字符可能是控制字符，替换为空格
                        console.log(`修复位置 ${i} 的异常字符: ${uint8Array[i].toString(16)}`);
                        uint8Array[i] = 0x20; // 空格
                    }
                }
            }
            
            // 2. 确保文件结构完整
            this.ensurePDFEnding(uint8Array);
            
            return uint8Array;
        },
        
        // 确保PDF文件正确结尾
        ensurePDFEnding(uint8Array) {
            const content = Array.from(uint8Array.slice(-10))
                .map(b => String.fromCharCode(b))
                .join('');
            
            if (!content.includes('%%EOF')) {
                console.log('文件缺少%%EOF标记');
                // 注意：这里不能直接修改uint8Array长度，需要返回新数组
                // 但为了简化，先记录问题
                console.warn('需要添加%%EOF标记，但当前方法不支持扩展数组');
            }
        },
        
        // 查找PDF头部结束位置
        findHeaderEnd(uint8Array) {
            try {
                for (let i = 0; i < Math.min(50, uint8Array.length); i++) {
                    if (uint8Array[i] === 0x0A || uint8Array[i] === 0x0D) {
                        return i + 1;
                    }
                }
                return 8; // 默认位置
            } catch (error) {
                return 8;
            }
        },
        
        // PDF数据诊断工具
        diagnosePDFData(data, source = '未知') {
            console.group(`PDF数据诊断 - 来源: ${source}`);
            console.log('数据类型:', typeof data);
            console.log('数据长度:', data ? data.length : 'N/A');
            
            if (typeof data === 'string') {
                console.log('字符串前100字符:', data.substring(0, 100));
                console.log('是否以%PDF开头:', data.startsWith('%PDF'));
                
                // 检查是否包含非ASCII字符
                const hasNonAscii = /[^\x20-\x7E]/.test(data);
                console.log('包含非ASCII字符:', hasNonAscii);
                
                if (hasNonAscii) {
                    console.warn('检测到非ASCII字符，可能需要特殊处理');
                }
            } else if (data instanceof Uint8Array) {
                console.log('Uint8Array前8字节:', Array.from(data.slice(0, 8)).map(b => b.toString(16)).join(' '));
                const header = Array.from(data.slice(0, 4)).map(b => String.fromCharCode(b)).join('');
                console.log('解析的文件头:', header);
            }
            
            console.groupEnd();
        },

        // 添加线性化PDF检测方法
        detectLinearizedPDF(uint8Array) {
            try {
                const text = new TextDecoder('latin1').decode(uint8Array.slice(0, 1024));
                return text.includes('/Linearized') || text.includes('Linearized');
            } catch (error) {
                console.warn('检测线性化PDF时出错:', error);
                return false;
            }
        },

        // 新增：带容错的PDF页面渲染
        async renderPDFPageWithFallback(pdfDoc, pageNum, canvasRef, scale = 1) {
            try {
                console.log('开始获取PDF页面:', pageNum);
                const page = await pdfDoc.getPage(pageNum);
                
                // 尝试获取页面内容信息
                try {
                    const textContent = await page.getTextContent();
                    console.log('页面文本内容项数:', textContent.items.length);
                    
                    const annotations = await page.getAnnotations();
                    console.log('页面注释数量:', annotations.length);
                    
                    // 获取页面操作列表（用于检测图形内容）
                    const operatorList = await page.getOperatorList();
                    console.log('页面操作数量:', operatorList.fnArray.length);
                    
                    if (textContent.items.length === 0 && annotations.length === 0 && operatorList.fnArray.length <= 1) {
                        console.warn('⚠️ 检测到空白页面，没有任何内容');
                        this.showEmptyPageMessage();
                        return;
                    }
                    
                } catch (contentError) {
                    console.warn('无法获取页面内容信息:', contentError.message);
                }
                
                const viewport = page.getViewport({ scale });
                console.log('视口大小:', viewport.width, 'x', viewport.height);
                
                let canvas;
                if (typeof canvasRef === 'string') {
                    canvas = this.$refs[canvasRef];
                    if (Array.isArray(canvas)) {
                        canvas = canvas[0];
                    }
                } else {
                    canvas = canvasRef;
                }
                
                if (!canvas) {
                    console.error('Canvas未找到:', canvasRef);
                    return;
                }
                
                console.log('Canvas找到，准备渲染...');
                const context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                
                // 清除Canvas并设置白色背景
                context.fillStyle = 'white';
                context.fillRect(0, 0, canvas.width, canvas.height);
                
                // 尝试多种渲染模式
                const renderModes = [
                    {
                        name: '标准渲染',
                        context: {
                            canvasContext: context,
                            viewport: viewport,
                            background: 'white',
                            intent: 'display'
                        }
                    },
                    {
                        name: '打印渲染',
                        context: {
                            canvasContext: context,
                            viewport: viewport,
                            background: 'white',
                            intent: 'print'
                        }
                    },
                    {
                        name: '强制渲染',
                        context: {
                            canvasContext: context,
                            viewport: viewport,
                            background: 'transparent',
                            intent: 'any',
                            renderInteractiveForms: true,
                            optionalContentConfigPromise: Promise.resolve(null)
                        }
                    }
                ];

                let renderSuccess = false;
                
                for (const mode of renderModes) {
                    try {
                        console.log(`尝试${mode.name}...`);
                        
                        // 重新清除Canvas
                        context.fillStyle = 'white';
                        context.fillRect(0, 0, canvas.width, canvas.height);
                        
                        const renderTask = page.render(mode.context);
                        await renderTask.promise;
                        
                        console.log(`${mode.name}完成`);
                        
                        // 检查渲染结果
                        const hasContent = await this.checkRenderResult(canvas);
                        if (hasContent) {
                            console.log(`✅ ${mode.name}成功，检测到内容`);
                            renderSuccess = true;
                            break;
                        } else {
                            console.log(`⚠️ ${mode.name}完成但无内容`);
                        }
                        
                    } catch (renderError) {
                        console.warn(`❌ ${mode.name}失败:`, renderError.message);
                        continue;
                    }
                }
                
                if (!renderSuccess) {
                    console.error('所有渲染模式都未产生可见内容');
                    this.showCorruptedPDFMessage();
                } 
                
            } catch (error) {
                console.error('渲染PDF页面失败:', error);
                this.showRenderErrorMessage(error);
            }
        },

        // 检查渲染结果是否有内容
        async checkRenderResult(canvas) {
            try {
                const context = canvas.getContext('2d');
                const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
                const pixels = imageData.data;
                
                // 检查是否有非白色像素
                for (let i = 0; i < pixels.length; i += 4) {
                    const r = pixels[i];
                    const g = pixels[i + 1];
                    const b = pixels[i + 2];
                    const alpha = pixels[i + 3];
                    
                    // 如果找到非白色且不透明的像素
                    if (alpha > 0 && (r < 250 || g < 250 || b < 250)) {
                        return true;
                    }
                }
                return false;
            } catch (error) {
                console.error('检查渲染结果失败:', error);
                return false;
            }
        },

        // 添加测试内容到Canvas
   

        // 显示空白页面消息
        showEmptyPageMessage() {
            this.$message.warning('PDF页面为空白，没有任何内容');
        },

        // 显示PDF损坏消息
        showCorruptedPDFMessage() {
            this.$message.error('PDF文件可能已损坏，无法显示内容');
        },

        // 显示渲染错误消息
        showRenderErrorMessage(error) {
            this.$message.error('PDF渲染失败: ' + error.message);
        },
        
        // 缓存相关方法
        loadFromCache() {
            const cachedData = localStorage.getItem('rdearftsopsin_cache');
            if (cachedData) {
                try {
                    const cache = JSON.parse(cachedData);
                    if (cache.aircraft_id) {
                        this.otherQuery.aircraft_id = cache.aircraft_id;
                    }
                    if (cache.facility_id) {
                        this.otherQuery.facility_id = cache.facility_id;
                    }
                    console.log('从缓存加载选择项:', cache);
                } catch (error) {
                    console.error('缓存数据解析失败:', error);
                }
            }
        },
        
        saveToCache() {
            const cacheData = {
                aircraft_id: this.otherQuery.aircraft_id,
                facility_id: this.otherQuery.facility_id,
                timestamp: Date.now()
            };
            localStorage.setItem('rdearftsopsin_cache', JSON.stringify(cacheData));
            console.log('保存选择项到缓存:', cacheData);
        }
    },
    
    // 组件销毁时清理PDF资源
    beforeDestroy() {
        // 清理PDF文档对象
        if (this.currentPdfDoc) {
            this.currentPdfDoc.destroy();
        }
    }
};
</script>

<style lang="scss" scoped>
.message {
    width: 198%;
    background: #f8f8f9;
                display: flex;
    overflow-x: scroll;
}

.activeClass {
    color: red;
}

::v-deep .el-table .el-table__body-wrapper::-webkit-scrollbar {
    height: 15px !important;
    /* 设置水平滚动条的高度 */
}

.dialog-footer {
    text-align: right;
}



// 简化的加载状态样式
.loading-container {
    margin-top: 20px;
}

.loading-card {
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
    
    .loading-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        height: 200px;
        color: #409EFF;
            
            i {
                font-size: 48px;
                margin-bottom: 15px;
            animation: rotating 2s linear infinite;
            }
            
            span {
                font-size: 16px;
                font-weight: 500;
        }
    }
}

// 主页面PDF显示样式
.pdf-display-container {
    margin-top: 20px;
}

.pdf-card {
    width: 100%;
    max-width: 1400px; // 从1200px增加到1400px
    margin: 0 auto;
    
    .pdf-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .pdf-title {
            font-size: 18px;
            font-weight: bold;
            color: #409EFF;
        }
        
        .pdf-controls {
            display: flex;
            align-items: center;
            gap: 10px;
            
            .page-info, .zoom-info {
                font-size: 14px;
                font-weight: 600;
                color: #606266;
                background: #f5f7fa;
                padding: 4px 8px;
                border-radius: 4px;
                border: 1px solid #e4e7ed;
                min-width: 60px;
                text-align: center;
            }
        }
    }
    
    .pdf-content {
        text-align: center;
        padding: 20px;
        background: #fafafa;
        
        .main-pdf-canvas {
            width: 100%;
            max-width: 1200px; // 从950px增加到1200px
            height: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            background: white;
            display: block;
            margin: 0 auto;
            border: 2px solid #409EFF;
            position: relative;
            z-index: 1;
        }
    }
}

.empty-container {
    margin-top: 49px;
    text-align: center;
}

// PDF对话框样式（保留用于可能的查看功能）
.dialog-pdf-canvas {
    max-width: 100%;
    height: auto;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

.dialog-pdf-controls {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 15px;
    margin-top: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .page-info, .zoom-info {
        font-size: 14px;
        font-weight: 600;
        color: #606266;
        background: white;
        padding: 5px 10px;
        border-radius: 6px;
        border: 1px solid #e4e7ed;
    }
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
